package com.niudong.esdemo.lucene;

import org.apache.lucene.codecs.compressing.CompressionMode;
import org.apache.lucene.codecs.compressing.Compressor;
import org.apache.lucene.store.ByteArrayDataOutput;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

//案例: 字符高效流一次读写一行.
/*
    涉及到的方法:
        BufferedReader类中的特有方法:
            public String readLine();   //一次读取一行, 结束标记是"换行符", 并返回读取到的内容(不包括换行符), 读不到返回null
        BufferedWriter类中的特有方法:
            public void newLine();      //根据当前操作系统给出对应的换行符. windows(\r\n), linux(\n), mac(\r>
 */
public class Demo05IO {
    public static void main(String[] args) throws Exception {
        //1. 创建输入流, 关联数据源文件.
        BufferedReader br = new BufferedReader(new FileReader("demo05/data/1.txt"));
        //2. 创建输出流, 关联目的地文件.
        BufferedWriter bw = new BufferedWriter(new FileWriter("demo05/data/3.txt"));
        //3. 定义变量, 记录读取到的内容(字节, 有效字节数, 字符, 有效字符数, 字符串).

        Compressor compressor = CompressionMode.HIGH_COMPRESSION.newCompressor();

        byte[] outPutBytes = new byte[8024];
        ByteArrayDataOutput dataOutput = new ByteArrayDataOutput(outPutBytes);
        String line = null;
        //4. 循环读取, 只要条件满足就一直读, 并将读取到的内容赋值给变量.
        while ((line = br.readLine()) != null) {
            //5. 将读取到的数据写入到 指定的目的地文件中.

            System.out.println(line);


            byte[] bytes = line.getBytes("UTF-8");
            compressor.compress(bytes,0,bytes.length,dataOutput);

            System.out.println(dataOutput.getPosition());
          //  bw.write(outPutBytes.);



            bw.append(new String(outPutBytes,0,dataOutput.getPosition(),"UTF-8"));
            dataOutput.reset(outPutBytes);
            bw.newLine();       //根据操作系统给出对应的换行符.
        }
        //6. 释放资源.
        br.close();
        bw.close();
    }
}
